import getPublicParams from './sign';
import _ from './common'

class Request {

    /**
     * 基本属性
     */
    constructor() {
        this.options = {
            method: 'GET',
            data:{}
        }
    }

    /**
     * GET、POST请求
     * @param url
     * @param method
     * @param data
     * @returns {Promise}
     */
    ajax({
         url,
         method = this.options.method,
         data = this.options.data} = this.options
    ){
        return new Promise((resolve, reject) => {
            // 获取公共参数
            let sign = getPublicParams();
            // 认证token
            let token = wx.getStorageSync('token')
            
            wx.request({
                url: _.host.baseApi + url,
                method: method,
                data: data,
                header: {
                    'content-type': 'application/json',
                    'token': token,
                    'sign': sign,
                    'appId': _.host.appId
                },
                success: (res) => {
                    let data = res.data;
                    // 根据请求状态码做相应的判断
                    if (data.code == 0) {
                        // 成功
                        resolve(data)
                    } else if (data.code == 401) {
                        // token失效
                        wx.removeStorageSync('token');
                        wx.removeStorageSync('userId');
                        wx.navigateTo({
                            url: '../login/login'
                        })
                        reject(res)
                    } else {
                        reject(res)
                    }
                },
                fail: (err) => {
                    reject(err)
                },
                complete: (res) => {

                }
            })
        })
    }

    /**
     * GET请求
     * @param url
     * @param data
     * @returns {Promise}
     */
    get(url,data = {}){
        return this.ajax({
           url,
           data,
           method:'GET'
        })
    }

    /**
     * POST请求
     * @param url
     * @param data
     * @returns {Promise}
     */
    post(url,data = {}){
        return this.ajax({
           url,
           data,
           method:'POST'
        })
    }

}

/**
 * 生成签名
 * @param params
 * @returns {*}
 */
function buildParams(params){
    let keyArr = [];
    for (let key in params) {
        keyArr.push(key);
    }
    keyArr = keyArr.sort();
    let keys = keyArr.map((v) => params[v] ? v + '=' +params[v] : '' ).join('&');
    return md5(keys);
}

export default new Request